﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectCloth.Entity;

namespace ProjectCloth.FrmUI
{
    public partial class AskPriceFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        private List<Entity.Product> productList = new List<Entity.Product>();
        public AskPriceFrm()
        {
            InitializeComponent();
            productList = db.Products.ToList();
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            //验证必要的头部信息是否为空
            //TODO
            //if (string.IsNullOrEmpty(CompanyNameTxt.Text))
            //{
            //    MessageBox.Show("公司名称不能为空");
            //    return;
            //}
            //if (string.IsNullOrEmpty(PhoneTxt.Text))
            //{
            //    MessageBox.Show("电话不能为空");
            //    return;
            //}
            //if (string.IsNullOrEmpty(LiaisonTxt.Text))
            //{
            //    MessageBox.Show("联系人不能为空");
            //    return;
            //}
            //if (string.IsNullOrEmpty(ProvinceTxt.Text))
            //{
            //    MessageBox.Show("省份不能为空");
            //    return;
            //}
            int count = 0;
            foreach (DataGridViewRow p in dataGridView1.Rows)
            {
                if (Helper.GetStringFromCell(p.Cells["ProductNo"]).Length > 0) count++;
            }
            if (count <= 0) MessageBox.Show("行不能为空");
            //验证 是否存在非空行
            //TODO
            List<AskPriceOrder> askPriceOrders = new List<AskPriceOrder>();
            foreach (DataGridViewRow p in dataGridView1.Rows)
            {
                if (Helper.GetStringFromCell(p.Cells["ProductNo"]).Length > 0)
                {
                    askPriceOrders.Add(new AskPriceOrder
                    {
                        Date = AskDate.Value.Date,
                        CompanyName = CompanyNameTxt.Text,
                        Phone = PhoneTxt.Text,
                        Liaison = LiaisonTxt.Text,
                        Province = ProvinceTxt.Text,
                        ProductNo = Helper.GetStringFromCell(p.Cells["ProductNo"]),
                        Quantity = Helper.GetDoubleFromCell(p.Cells["Quantity"]),
                        ColorType = Helper.GetStringFromCell(p.Cells["ColorType"]),
                        Factory = Helper.GetStringFromCell(p.Cells["Factory"]),
                        ProductNoB = Helper.GetStringFromCell(p.Cells["ProductNoB"]),
                        ProductCost = Helper.GetStringFromCell(p.Cells["ProductCost"]),
                        BatchPrice = Helper.GetDecimalFromCell(p.Cells["BatchPrice"]),
                        Price = Helper.GetDecimalFromCell(p.Cells["Price"]),
                        Remark = Helper.GetStringFromCell(p.Cells["Remark"])
                    });
                }
            }
            db.AskPriceOrders.AddRange(askPriceOrders);
            var result = db.SaveChanges();
            if (result > 0)
                MessageBox.Show("保存成功！");
            else MessageBox.Show("保存失败！");
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {

        }
        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            var dgv = dataGridView1;
            bool _disable = false;

            switch (keyData)
            {
                case Keys.Enter:
                    if (dgv.CurrentRow != null)
                    {
                        if (dgv.CurrentRow.Cells["ProductNo"] != null && dgv.CurrentRow.Cells["ProductNo"].Value != null)
                        {

                            var productno = dgv.CurrentRow.Cells["ProductNo"].Value.ToString();
                            var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();// productlist.Where(p => p.ProductId == productno).FirstOrDefault();
                            if (product != null)//&& sel)
                            {
                                //if (dgv.CurrentRow.Cells["ProductName"].Value == null && dgv.CurrentRow.Cells["Price"].Value == null)
                                {
                                    dgv.CurrentRow.Cells["Price"].Value = product.Price;
                                    dgv.CurrentRow.Cells["BatchPrice"].Value = product.BatchPrice;
                                    dgv.CurrentRow.Cells["Factory"].Value = product.Producer;
                                    dgv.CurrentRow.Cells["ProductCost"].Value = product.ProductCost;
                                    dgv.CurrentRow.Cells["ProductNoB"].Value = product.ProductNoB;
                                }
                            }
                            if (dgv.CurrentRow.Cells["Quantity"].Selected == true)
                            {
                                dgv.CurrentCell = dgv.CurrentRow.Cells["Remark"];
                            }
                            else SendKeys.Send("{Tab}");

                        }

                    }
                    else
                    {
                        if (ProvinceTxt.Focused == true)
                        {
                            dgv.Focus();
                        }
                        SendKeys.Send("{Tab}");

                    }

                    _disable = true;
                    break;
                case Keys.F10:
                    {
                        ClearBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                case Keys.F12:
                    {
                        SaveBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                default:
                    break;
            }

            return _disable;
        }
        #endregion

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
                if (!string.IsNullOrEmpty(form.productNo)) { LoadGvd(); }
            }
        }

        private void ClearBtn_Click(object sender, EventArgs e)
        {
            CompanyNameTxt.Text = "";
            PhoneTxt.Text = "";
            LiaisonTxt.Text = "";
            ProvinceTxt.Text = "";
            dataGridView1.Rows.Clear();
            CompanyNameTxt.Focus();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && dataGridView1.Rows[e.RowIndex].Cells["QueryBtn"].Selected == true)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
            }
        }
        public List<SaleTableModel> getSql()
        {
            var orderproductnoTxt = dataGridView1.CurrentRow.Cells["ProductNo"].Value as string;
            var startTime = DateTime.Now.AddYears(-1);// startDatePiker.Value.Date;
            var endTime = DateTime.Now.AddDays(1).Date;// endDatePicker.Value.AddDays(1).Date;
            var instockNo = "";// InstockNoTxt.Text != null ? InstockNoTxt.Text : "";
            //var isPay = statusCombobox.SelectedValue != null ? ((int)statusCombobox.SelectedValue == 0 ? false : true) : false;
            var selCompanyId = 0;// companyCbb.SelectedValue != null ? (int)companyCbb.SelectedValue : 0;
            var list = (from oi in db.SaleOrderItems//.ToList()
                        join o in db.SaleOrders on oi.OrderId equals o.Id
                        join s in db.InStockItems on oi.Id equals s.SaleOrderItemId into os
                        from osi in os.DefaultIfEmpty()
                        join pr in db.Products on oi.ProductId equals pr.Id
                        where o.RecordDate > startTime && o.RecordDate < endTime && o.OrderStatus != 2
                        //&& (string.IsNullOrEmpty(instockNo) || osi.InstockItemNo.Contains(instockNo))
                        //&& (string.IsNullOrEmpty(orderNoTxt.Text) || oi.OrderNo.Contains(orderNoTxt.Text))
                        && (string.IsNullOrEmpty(orderproductnoTxt) || pr.ProductNo.Contains(orderproductnoTxt))
                        //&& (string.IsNullOrEmpty(InstockproductTxt.Text) || osi.InstockProductName.Contains(InstockproductTxt.Text))
                        && (selCompanyId == 0 || osi.CompanyId == selCompanyId)
                        //&& (statusCombobox.SelectedValue == null || isPay == (o.OrderStatus == 0 ? false : true))
                        select new SaleTableModel
                        {
                            SaleColorType = oi.ColorType,
                            ColorType = osi.ColorType,
                            SaleOrderRemark = o.Remark,
                            Summary = o.Summary + "|" + o.CompanyName + "|" + o.Liaison + "|" + o.Phone,
                            Amount = oi.Amount,
                            Price = oi.Price,
                            SaleOrderNo = o.OrderNo,
                            saleProduct = pr.ProductNo,
                            Remark = o.Remark,
                            Time = o.RecordDate,
                            Status = o.OrderStatus == 1 ? "已收款" : "未收款",
                            Id = o.Id,
                            SaleItemRemark = oi.Remark,
                            SaleQuantity = oi.Quantity,
                            CompanyName = osi.CompanyNo != null ? osi.CompanyNo : "",
                            InStockNo = osi.InstockItemNo != null ? osi.InstockItemNo : "",
                            InStockProductName = osi.InstockProductName != null ? osi.InstockProductName : "",
                            InstockPrice = osi.Price != null ? osi.Price : 0,
                            Quantity = osi.Quantity != null ? osi.Quantity : 0,
                            InstockAmount = osi.Amount != null ? osi.Amount : 0
                        }).ToList();
            return list;
        }
        private void LoadGvd()
        {
            dataGridView2.AutoGenerateColumns = false;
            var list = getSql();
            dataGridView2.DataSource = list;
        }
        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
